<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%
	String path = request.getContextPath();
	String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
	<meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="initial-scale=1.0, user-scalable=no, width=device-width">
	<link rel="stylesheet" href="stoneframe/styles/learun-ui.css">
    <link rel="stylesheet" href="stoneframe/scripts/bootstrap/bootstrap.min.css">
	<link rel="stylesheet" type="text/css" href="stoneframe/scripts/plugins/dataTables1.10.15/media/css/dataTables.bootstrap.css" /> 
    <link rel="stylesheet" href="http://cache.amap.com/lbs/static/main1119.css"/>
	
    <style type="text/css">
        #tip {
            background-color: #fff;
            padding:10px 10px;
            border: 1px solid silver;
            box-shadow: 3px 4px 3px 0px silver;
            position: absolute;
            font-size: 12px;
            right: 20px;
            top: 40px;
            border-radius: 3px;
            line-height: 36px;
            width:450px;
        }
    </style>
    <script src="http://webapi.amap.com/maps?v=1.3&key=857fce8ded133c1a7e2ab20d5c626dcd&&plugin=AMap.Scale,AMap.OverView,AMap.ToolBar,AMap.Autocomplete,AMap.PolyEditor,AMap.CircleEditor,AMap.MouseTool"></script>
    <script src="stoneframe/scripts/jquery/jQuery-2.2.0.min.js"></script>
	<script src="stoneframe/scripts/bootstrap/bootstrap.min.js"></script>
	<script src="stoneframe/scripts/plugins/dataTables1.10.15/media/js/jquery.dataTables.js"></script>
	<script src="stoneframe/scripts/plugins/dataTables1.10.15/media/js/dataTables.bootstrap.js"></script>
	<script src="stoneframe/scripts/utils/learun-ui.js"></script>
	<script src="stoneframe/scripts/utils/learun-form.js"></script>
  </head>
<body>
<div id="container"></div>

<div id="tip">
    <button type="button" class="btn btn-primary btn-sm" data-toggle="modal" data-target="#myModal">绘制围栏</button>
    <table id="example" class="table acelistTable"> 
		<thead>  
			<tr>
				<th style="width:90px;"></th> 
				<th>用户编码</th>  
				<th>围栏名称</th>   
			</tr>  
		 </thead>  
		 <tbody></tbody>   
   </table> 
</div>

<div class='button-group' style="background-color: #0d9bf2;right: 700px;top: 20px;height:45px;">
        <input id="cityName" class="inputtext" placeholder="请输入城市的名称" type="text"/>
        <input id="query" class="button" value="搜索" type="button"/>
</div>

<!-- 模态框（Modal） -->
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true" style="text-align:center;">
	<div class="modal-dialog">
		<div class="modal-content">
			<div class="modal-header">
				<button type="button" class="close" data-dismiss="modal" aria-hidden="true">
					&times;
				</button>
				<h4 class="modal-title" id="myModalLabel">
                <div class="btn-group">
                    <button type="button" class="btn btn-default" id="btnRect">矩形</button>
                    <button type="button" class="btn btn-default" id="btnCircle">圆形</button>
                    <button type="button" class="btn btn-default" id="btnArea">多边形</button>
                </div>
				</h4>
			</div>
		</div><!-- /.modal-content -->
	</div><!-- /.modal -->
</div>

<!-- 添加围栏模态框（Modal） -->
<div class="modal fade" id="areaModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
	<div class="modal-dialog">
		<div class="modal-content">
			<div class="modal-header">
				<button type="button" class="close" data-dismiss="modal" 
						aria-hidden="true">×
				</button>
				<h4 class="modal-title" id="H1">
					添加围栏
				</h4>
			</div>
			<div class="modal-body">
				<form class="form-horizontal" role="form" id="form1">
                    <input id="fenceId" type="hidden" value="" />
                    <input id="fenceRule" type="hidden" />
                    <input id="mapType" type="hidden" value="2" />

	                <div class="form-group">
		                <label for="fenceName" class="col-sm-3 control-label"><span style="color:red">*</span>围栏名称：</label>
		                <div class="col-sm-9">
			                <input type="text" class="form-control" id="fenceName" placeholder="请输入围栏名称">
		                </div>
	                </div>
	                <div class="form-group">
		                <label for="category" class="col-sm-3 control-label">围栏类型：</label>
		                <div class="col-sm-9">
                            <input id="category" type="hidden" />
			                <input type="text" class="form-control" id="categoryVal" placeholder="请输入围栏类型" disabled="disabled">
		                </div>
	                </div>
                    <div class="form-group">
		                <label for="fenceAlarm" class="col-sm-3 control-label">报警类型：</label>
		                <div class="col-sm-9">
                            <select class="form-control" id="fenceAlarm">
                              <option value="0">进</option>
                              <option value="1">出</option>
                              <option value="2" selected>进出</option>
                            </select>
		                </div>
	                </div>
                    <div class="form-group">
		                <label for="fenceLimit" class="col-sm-3 control-label">限时：</label>
		                <div class="col-sm-9">
                            <select class="form-control" id="fenceLimit">
                              <option value="0" selected>不限制</option>
                            </select>
		                </div>
	                </div>
                    <div class="form-group" style="display:none" id="limit_flag_time">
		                <label for="lowLimit" class="col-sm-3 control-label">开始时间：</label>
                        <div class="col-sm-3">
			                <input type="text" class="form-control" id="lowLimit" value=" " placeholder="开始时间">
                        </div>
                        <label for="highLimit" class="col-sm-2 control-label">结束时间</label>
                        <div class="col-sm-4">
			                <input type="text" class="form-control" id="highLimit" value=" " placeholder="结束时间">
                        </div>
	                </div>
                </form>
			</div>
			<div class="modal-footer">
				<button type="button" class="btn btn-default" 
						data-dismiss="modal">关闭
				</button>
				<button type="button" class="btn btn-primary" onclick="btn_save();">
					保存
				</button>
			</div>
		</div><!-- /.modal-content -->
	</div><!-- /.modal-dialog -->
</div><!-- /.modal -->

<script>
	$(function () {
        $('#areaModal').on('hide.bs.modal',
        function () {
            mouseTool.close(true);
        })
    });

    var map = new AMap.Map("container", {
        resizeEnable: true,
        zoom:14
    });
	
	var scale = new AMap.Scale({
        visible: true
    });
    map.addControl(scale);

    var toolBar = new AMap.ToolBar({
        visible: true
    });
    map.addControl(toolBar);

    var overView = new AMap.OverView({
        visible: true
    });
    map.addControl(overView);
	
	 //设置城市
    AMap.event.addDomListener(document.getElementById('query'), 'click', function() {
        var cityName = document.getElementById('cityName').value;
        if (!cityName) {
            cityName = '北京市';
        }
        map.setCity(cityName);
    });
	
	var auto = new AMap.Autocomplete({
        input: "cityName"
    });
    AMap.event.addListener(auto, "select", select);//注册监听，当选中某条记录时会触发
    function select(e) {
        if (e.poi && e.poi.location) {
            map.setZoom(14);
            map.setCenter(e.poi.location);
        }
    }
	
	var mouseTool = new AMap.MouseTool(map);
    AMap.event.addListener(mouseTool, "draw", function callback(e) {
        var eObject = e.obj;//obj属性就是鼠标事件完成所绘制的覆盖物对象。
        console.log(eObject);
        if (eObject.CLASS_NAME == "AMap.Circle") { //圆形
            var radius = eObject.Hi.radius;
            var lat = eObject.Hi.center["lat"];
            var lng = eObject.Hi.center["lng"];
            var detail = "{radius:" + radius + ",lat:" + lat + ",lng:" + lng + "}";
            $("#fenceRule").val(detail);
            console.log(detail);
        } else if (eObject.CLASS_NAME == "AMap.Polygon") { //多边形
            var path = JSON.stringify(eObject.Hi.path);
            $("#fenceRule").val(path);
            console.log(path);
        }
        $("#areaModal").modal('show');
    });
	
	//0圆形，1矩形，2多边形
    var btnRectListener = AMap.event.addDomListener(document.getElementById("btnRect"), 'click', function () {
        $("#category").val(2);
        $("#categoryVal").val("矩形");
        $('#myModal').modal('hide');
        mouseTool.rectangle();
    });//给div绑定单击事件
    var btnCircleListener = AMap.event.addDomListener(document.getElementById("btnCircle"), 'click', function () {
        $("#category").val(1);
        $("#categoryVal").val("圆形");
        $('#myModal').modal('hide');
        mouseTool.circle();
    });//给div绑定单击事件
    var btnAreaListener = AMap.event.addDomListener(document.getElementById("btnArea"), 'click', function () {
        $("#category").val(3);
        $("#categoryVal").val("多边形");
        $('#myModal').modal('hide');
        mouseTool.measureArea();
    });//给div绑定单击事件
	
	function btnCircle(id) {
        $.SetForm({
			url: "<%=basePath%>trafFence/get.do",
			param: { keyValue: id },
			success: function (data) {
				if(data.type=="0"){
					if (data.rows.fenceRule) {
						if (data.rows.category == 1) {
							drawCircle(data.rows)
						} else if (data.rows.category == 3 || data.rows.category == 2) {
							drawPolygon(data.rows)
						}
					}
				}else{
					dialogAlert(data.message, -1);
				}
			}
		});
    }

    //画圆
    function drawCircle(data) {
        var contextMenu = new AMap.ContextMenu();  //创建右键菜单
        //右键放大
        contextMenu.addItem("编辑围栏", function () {
            circleEditor.open();
        }, 0);
        //右键缩小
        contextMenu.addItem("保存围栏", function () {
            console.log(circle);
            var id = circle.Hi.id;
            var radius = circle.Hi.radius;
            var lat = circle.Hi.center["lat"];
            var lng = circle.Hi.center["lng"];
            var fenceRule = "{radius:" + radius + ",lat:" + lat + ",lng:" + lng + "}";
			$.SaveForm({
				url: "<%=basePath%>trafFence/editRule.do",
				param: { fenceRule: fenceRule, keyValue: id },
				loading: "正在保存数据...",
				success: function () {
					circleEditor.close();
                    //circle.hide();
					//dialogMsg(data.Message, 0);
				}
			});
        }, 1);
        //右键缩小
        contextMenu.addItem("取消编辑", function () {
            circleEditor.close();
        }, 2);
        //右键缩小
        contextMenu.addItem("关闭", function () {
            circleEditor.close();
            circle.hide();
        }, 3);
        var obj = eval('(' + data.fenceRule + ')');
        var circle = new AMap.Circle({
            id: data.fenceId,
            center: new AMap.LngLat(obj.lng, obj.lat),// 圆心位置
            radius: obj.radius, //半径
            strokeColor: "#F33", //线颜色
            strokeOpacity: 0.5, //线透明度
            strokeWeight: 3, //线粗细度
            fillColor: "#ee2200", //填充颜色
            fillOpacity: 0.35//填充透明度
        });
        map.setZoom(14);
        var circleEditor = new AMap.CircleEditor(map, circle);
        circle.setMap(map);
        map.setCenter([obj.lng, obj.lat]);
        map.setFitView();
        circle.on('rightclick', function (e) {
            contextMenu.open(map, e.lnglat);
        });
    }

    //drawPolygon();
    //画多边形
    function drawPolygon(data) {
        var contextMenu = new AMap.ContextMenu();  //创建右键菜单
        //右键放大
        contextMenu.addItem("编辑围栏", function () {
            polygonEditor.open();
        }, 0);
        //右键缩小
        contextMenu.addItem("保存围栏", function () {
            console.log(polygon);
            polygonEditor.close();
        }, 1);
        //右键缩小
        contextMenu.addItem("取消编辑", function () {
            polygonEditor.close();
        }, 2);
        //右键缩小
        contextMenu.addItem("关闭", function () {
            polygon.hide();
        }, 3);
        var obj = eval(data.vertexes);
        var polygonArr = new Array();//多边形覆盖物节点坐标数组
        for (var i = 0; i < obj.length; i++) {
            polygonArr.push([obj[i].lng, obj[i].lat]);
        }
        //polygonArr.push([116.403322, 39.920255]);
        //polygonArr.push([116.410703, 39.897555]);
        //polygonArr.push([116.402292, 39.892353]);
        //polygonArr.push([116.389846, 39.891365]);
        var polygon = new AMap.Polygon({
           
            path: polygonArr,//设置多边形边界路径
            strokeColor: "#FF33FF", //线颜色
            strokeOpacity: 0.5, //线透明度
            strokeWeight: 3,    //线宽
            fillColor: "#ee2200", //填充色
            fillOpacity: 0.35//填充透明度
        });
        map.setZoom(14);
        polygon.setMap(map);
        var polygonEditor = new AMap.PolyEditor(map, polygon);
        polygon.on('rightclick', function (e) {
            contextMenu.open(map, e.lnglat);
        });
    }
	
	function btn_save() {
        var fenceName = $("#fenceName").val();
        if (!fenceName) {
			dialogAlert("围栏名称必须填写！", -1);
            return;
        }
        window.setTimeout(function () {
            var postData = $("#form1").GetWebControls();
			$.SaveForm({
				url: "<%=basePath%>trafFence/edit.do?keyValue=" + $("#fenceId").val(),
				param: postData,
				loading: "正在保存数据...",
				success: function () {
					$('#example').dataTable().api().ajax.reload();
					$('#areaModal').modal('hide');
					//dialogMsg(data.Message, 0);
				}
			});
        }, 200); 
    }
	
	function btnEdit(id) {
		$.SetForm({
			url: "<%=basePath%>trafFence/get.do",
			param: { keyValue: id },
			success: function (data) {
				if(data.type=="0"){
					if(data.type=="0"){
						$("#form1").SetWebControls(data.rows);
						$('#areaModal').modal('show');
					}else{
						dialogAlert(data.message, -1);
					}
				}else{
					dialogAlert(data.message, -1);
				}
			}
		});
    }

    function btnDelete(id) {
		$.RemoveForm({
			url: "<%=basePath%>trafFence/del.do",
			param: { keyValue: id },
			success: function (data) {
				 $('#example').dataTable().api().ajax.reload();
			}
		});
    }
	
</script>

<script>
	$(function () {
		var keeperUserList = $('#example').DataTable({                    
			ajax: {
				url: "<%=basePath%>trafFence/listPage.do",
				type:"POST",
				dataType: "json",
				// 传入已封装的参数  
				data: function(data){  
					data.page = data.start / data.length + 1;  
					data.limit = data.length; 
					// 右上角搜索  
					data.keyword = data.search.value;  
					//data.version = CONSTANT.APISERVER.KEEPER;  
					delete data.columns;  
				},
				dataSrc : function(result) {  
					// 后台不实现过滤功能，每次查询均视作全部结果  
					result.recordsTotal = result.records;  
					result.recordsFiltered = result.records || 0;  
					result.data = result.rows || {};  
					delete result.records;  
					delete result.rows;  
					return result.data;  
				} 
			},
			scrollX : true,  
			// 每次对 datatable 进行操作时也是请求后台  
			serverSide : true,  
			// 加载状态  
			processing : false,  
			// 默认排序查询,为空则表示取消默认排序否则复选框一列会出现小箭头  
			order: [],  
			// 分页,默认打开  
			paging : true,  
			// 是否禁用原生搜索  
			searching: true,  
			language : CONSTANT.DATA_TABLES.DEFAULT_OPTION.LANGUAGE, 
			lengthChange: false,
			info: false,
			autoWidth: false,
			pageLength: 10,
			columns : [
				{  
					data : 'operate',  
					bSortable : false,    
					width : '90px',  
					render : function(data, type, full) {  
						if (!full.fenceId) {  
							return '';  
						}   
						var result = "<a href='javascript:void(0);' onclick='btnCircle(\"" + full.fenceId + "\")' class='btn-sm'>显示</a>&nbsp;" + "<a href='javascript:void(0);' onclick='btnEdit(\"" + full.fenceId + "\")' class='btn-sm'>修改</a>" + "<a href='javascript:void(0);' onclick='btnDelete(\"" + full.fenceId + "\")' class='btn-sm'>删除</a>";  
						return result;  
					}   
				},
				{  
					data : 'fenceName',  
					bSortable : false,  
					width : "100px"
				},  
				{  
					data : 'fenceName',  
					bSortable : false,  
					width : "100px",  
				}
			],
			drawCallback : function() {  
				// 取消全选  
				$(":checkbox[name='keeperUserGroup-checkable']").prop('checked', false);  
			},  
			createdRow : function(row, data, dataIndex) {  
				if (data.status == 1) {  
					// 已冻结  
					$(row.children[7]).addClass('danger');  
				} else if (data.status == 2) {  
					// 已停用  
					$(row.children[7]).addClass('warning');  
				} else if (data.status == 3) {  
					// 已注销   
					$(row.children[7]).addClass('error');  
				}  
			},  
			buttons : [   
				{  
					text : '<li class="fa fa-plus"></li> 新增',  
					titleAttr : '新增管家账号',  
					className : "btn green",  
					action: function ( e, dt, node, config ) {  
						keeperUserIsupdate = false;  
						clearKeeperUserFormData();  
						// 重置form校验  
						FormValidation.resetForm();  
						$('#editKeeperUserWin .modal-title').text('新增管家信息');  
						$('#editKeeperUserWin').modal('show');  
					}  
				}, {  
					text : '<li class="fa fa-search"></li> 搜索',  
					titleAttr : '按条件搜索',  
					className : "btn btn-sm green btn-outline filter-submit margin-bottom",  
					action: function ( e, dt, node, config ) {  
						$('#queryKeeperUserWin').modal({  
							show : true  
						});  
					}  
				}, {  
					extend : "print",  
					className : "btn dark btn-outline"  
				}, {  
					extend : "pdf",  
					className : "btn green btn-outline"  
				}, {  
					extend : "excel",  
					className : "btn yellow btn-outline"  
				}   
			],  
			dom:"<'row' <'col-md-12'B>><'row'<'col-md-6 col-sm-12'l><'col-md-6 col-sm-12'f>r><'table-scrollable't><'row'<'col-md-5 col-sm-12'i><'col-md-7 col-sm-12'p>>" 
		});
		// 如果 scrollX : true 使用这个$('#keeperUserList_wrapper').on("change", ":checkbox", function() {  
		// 如果 scrollX : false $('#keeperUserList').on("change", ":checkbox", function() {   
		// 因为  scrollX : true 为true加了滚动条，表头和表体成了两个表格，这个可以查看代码就知道  
		$('#keeperUserList_wrapper').on("change", ":checkbox", function() {  
			// 列表复选框  
			if ($(this).is("[name='keeperUserGroup-checkable']")) {  
				// 全选  
				$(":checkbox", '#keeperUserList').prop("checked",$(this).prop("checked"));  
			}else{  
				// 一般复选  
				var checkbox = $("tbody :checkbox", '#keeperUserList');  
				$(":checkbox[name='cb-check-all']", '#keeperUserList').prop('checked', checkbox.length == checkbox.filter(':checked').length);  
			}  
		}).on('preXhr.dt', function(e, settings, data) {  
			// ajax 请求之前事件  
			data.page = data.start / data.length + 1;  
			data.limit = data.length;  
			data.version = CONSTANT.APISERVER.KEEPER;  
			delete data.columns;  
		});  
		  
		// 搜索框事件  
		$('#keeperUserList_filter input').unbind().keyup(function() {  
			var params = {};  
				  
			if ($(this).val().trim()) {  
				params.keyword = $(this).val().trim();  
			}  
			keeperUserList.settings()[0].ajax.data = params;  
			keeperUserList.ajax.reload();  
		}); 
	});
	/** 
	 * 搜索 这个搜索解决datatable自定义搜索 
	 */  
	function queryKeeperUserList() {  
	  
		// 添加参数  
		var params = {};  
		  
		if ($('#queryKeeperUserName').val()) {  
			params.name = $('#queryKeeperUserName').val();  
		}  
		if ($('#queryKeeperUserPhone').val()) {  
			params.phone = $('#queryKeeperUserPhone').val();  
		}  
		if ($('#queryKeeperUserStatus').val() != '') {  
			params.status = $('#queryKeeperUserStatus').val();  
		}  
		if ($('#queryKeeperUserPosition').val() != '') {  
			params.position = $('#queryKeeperUserPosition').val();  
		}  
		if ($('#queryKeeperUserOrderBy').val()) {  
			params.orderBy = $('#queryKeeperUserOrderBy').val();  
		}  
	  
		keeperUserList.settings()[0].ajax.data = params;  
		keeperUserList.ajax.reload();  
		$('#queryKeeperUserWin').modal('hide');  
	}  
	
	var CONSTANT = {  
          
    // datatables常量  
    DATA_TABLES : {  
        DEFAULT_OPTION : { // DataTables初始化选项  
            LANGUAGE : {  
                sProcessing : "处理中...",  
                sLengthMenu : "显示 _MENU_ 项结果",  
                sZeroRecords : "没有匹配结果",  
                sInfo : "显示第 _START_ 至 _END_ 项结果，共 _TOTAL_ 项",  
                sInfoEmpty : "显示第 0 至 0 项结果，共 0 项",  
                sInfoFiltered : "(由 _MAX_ 项结果过滤)",  
                sInfoPostFix : "",  
                sSearch : "搜索:",  
                sUrl : "",  
                sEmptyTable : "表中数据为空",  
                sLoadingRecords : "载入中...",  
                sInfoThousands : ",",  
                oPaginate : {  
                    sFirst : "首页",  
                    sPrevious : "上页",  
                    sNext : "下页",  
                    sLast : "末页"  
                },  
                "oAria" : {  
                    "sSortAscending" : ": 以升序排列此列",  
                    "sSortDescending" : ": 以降序排列此列"  
                }  
            },  
            // 禁用自动调整列宽  
            autoWidth : false,  
            // 为奇偶行加上样式，兼容不支持CSS伪类的场合  
            stripeClasses : [ "odd", "even" ],  
            // 取消默认排序查询,否则复选框一列会出现小箭头  
            order : [],  
            // 隐藏加载提示,自行处理  
            processing : false,  
            // 启用服务器端分页  
            serverSide : true,  
            // 禁用原生搜索  
            searching : false  
        },  
        COLUMN : {  
            // 复选框单元格  
            CHECKBOX : {  
                className: "td-checkbox",  
                orderable : false,  
                bSortable : false,  
                data : "id",  
                render : function(data, type, row, meta) {  
                    var content = '<label class="mt-checkbox mt-checkbox-single mt-checkbox-outline">';  
                    content += '    <input type="checkbox" class="group-checkable" value="' + data + '" />';  
                    content += '    <span></span>';  
                    content += '</label>';  
                    return content;  
                }  
            }  
        },  
        // 常用render可以抽取出来，如日期时间、头像等  
        RENDER : {  
            ELLIPSIS : function(data, type, row, meta) {  
                data = data || "";  
                return '<span title="' + data + '">' + data + '</span>';  
            }  
        }  
    }  
};  
	
</script>
</body>
</html>
